package notentool;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;

import notentool.QISDataHandler.SemNote;


@SuppressWarnings("serial")
public class StudentView extends JFrame {
	protected JTable tableModules;
	protected Diagram panelDiagram;
	// the buttons
	protected JButton btnLoadAndUpdateData;
	protected JButton btnSetLogin;
	JButton btnDatenSpeichern;
	JButton btnDatenLadenlokal;
	JButton btnBeenden;
	JButton  btnDelTempData;
	JProgressBar progressBar;
	
	// popups
	protected PopupLogin popLogin;
	protected PopupSaveFile popSave;
	
	protected JTextPane textPanelStatistics;
	
	/* now it's possible to add the same checkbox in different popups*/
	protected JCheckBox chckbxSaveNoLogin; // chkbx for popups
	//ArrayList<SemNote> semNoten = null;
	
	public StudentView(){
		setTitle("Notenmanager");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize( new Dimension(640, 480) );
		getContentPane().setLayout(new BorderLayout(0, 0));
		
		JToolBar toolBar = new JToolBar();
		getContentPane().add(toolBar, BorderLayout.NORTH);
		
		progressBar = new JProgressBar();
		progressBar.setStringPainted(true);
		getContentPane().add(progressBar, BorderLayout.SOUTH);
		
		JPanel JPanelButtonContainer = new JPanel();
		getContentPane().add(JPanelButtonContainer, BorderLayout.WEST);
		GridBagLayout gbl_JPanelButtonContainer = new GridBagLayout();
		gbl_JPanelButtonContainer.columnWidths = new int[]{0, 0};
		gbl_JPanelButtonContainer.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
		gbl_JPanelButtonContainer.columnWeights = new double[]{0.0, Double.MIN_VALUE};
		gbl_JPanelButtonContainer.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		JPanelButtonContainer.setLayout(gbl_JPanelButtonContainer);
		
		btnLoadAndUpdateData = new JButton("Noten laden (QIS)");
		btnLoadAndUpdateData.setToolTipText("Noten herunterladen");
		btnLoadAndUpdateData.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				System.out.println("Button gedrückt");
				
				//if (  < table.getRowCount()-1 )
				//    ( (DefaultTableModel) table.getModel() ).insertRow(dest+1, getValuesForNewRow());
				//  else
				//    ( (DefaultTableModel) table.getModel() ).addRow(getValuesForNewRow());
			//	((DefaultTableModel) tableModules.getModel()).addRow(null);
			}
		});
		
		btnSetLogin = new JButton("Login setzen");
		btnSetLogin.setToolTipText("Matrikelnummer und Passwort");
		GridBagConstraints gbc_btnLoginSetzen = new GridBagConstraints();
		gbc_btnLoginSetzen.fill = GridBagConstraints.BOTH;
		gbc_btnLoginSetzen.insets = new Insets(0, 0, 5, 0);
		gbc_btnLoginSetzen.gridx = 0;
		gbc_btnLoginSetzen.gridy = 1;
		JPanelButtonContainer.add(btnSetLogin, gbc_btnLoginSetzen);
		
		GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
		gbc_btnNewButton.fill = GridBagConstraints.HORIZONTAL;
		gbc_btnNewButton.insets = new Insets(0, 0, 5, 0);
		gbc_btnNewButton.gridx = 0;
		gbc_btnNewButton.gridy = 2;
		JPanelButtonContainer.add(btnLoadAndUpdateData, gbc_btnNewButton);
		
		btnDatenLadenlokal = new JButton("Daten laden (Lokal)");
		btnDatenLadenlokal.setEnabled(true);
		GridBagConstraints gbc_btnDatenLadenlokal = new GridBagConstraints();
		gbc_btnDatenLadenlokal.insets = new Insets(0, 0, 5, 0);
		gbc_btnDatenLadenlokal.gridx = 0;
		gbc_btnDatenLadenlokal.gridy = 3;
		JPanelButtonContainer.add(btnDatenLadenlokal, gbc_btnDatenLadenlokal);
		
		btnDatenSpeichern = new JButton("Daten speichern");
		btnDatenSpeichern.setToolTipText("Daten (einschließlich login) speichern");
		GridBagConstraints gbc_btnDatenSpeichern = new GridBagConstraints();
		gbc_btnDatenSpeichern.fill = GridBagConstraints.HORIZONTAL;
		gbc_btnDatenSpeichern.insets = new Insets(0, 0, 5, 0);
		gbc_btnDatenSpeichern.gridx = 0;
		gbc_btnDatenSpeichern.gridy = 4;
		JPanelButtonContainer.add(btnDatenSpeichern, gbc_btnDatenSpeichern);
		
		btnDelTempData = new JButton("Cache löschen");
		btnDelTempData.setEnabled(false);
		btnDelTempData.setToolTipText("Temporäre Daten löschen");
		GridBagConstraints gbc_btnDatenLschen = new GridBagConstraints();
		gbc_btnDatenLschen.fill = GridBagConstraints.HORIZONTAL;
		gbc_btnDatenLschen.insets = new Insets(0, 0, 5, 0);
		gbc_btnDatenLschen.gridx = 0;
		gbc_btnDatenLschen.gridy = 5;
		JPanelButtonContainer.add(btnDelTempData, gbc_btnDatenLschen);
		
		btnBeenden = new JButton("Beenden");
		GridBagConstraints gbc_btnBeenden = new GridBagConstraints();
		gbc_btnBeenden.insets = new Insets(0, 0, 5, 0);
		gbc_btnBeenden.fill = GridBagConstraints.HORIZONTAL;
		gbc_btnBeenden.gridx = 0;
		gbc_btnBeenden.gridy = 6;
		JPanelButtonContainer.add(btnBeenden, gbc_btnBeenden);
		
		JTabbedPane tabbedPaneContent = new JTabbedPane(JTabbedPane.TOP);
		getContentPane().add(tabbedPaneContent, BorderLayout.CENTER);
		
		Object[][] rowData = {
		// example content	
		/*		{"Erster", "Test", "Eintrag", "bla", "hier", "die", "zeile", "versuch", "datum", "ects"}, 
				{"Test"},
				{"Eintrag"}, 
				{"bla"},
				{"null"},
				{null},
				{null},
				{null},
				{null},
				{null},
				{null}
		*/
		};
				
		String[] columnNames =  {
				"Modulnr.", "Modultext", "Semester", "Note", "Status", "Credits", "Vermerk", "Versuch", "Datum", "ECTS"
				};
		
		tableModules = new JTable();
		tableModules.setSurrendersFocusOnKeystroke(true);
		tableModules.setColumnSelectionAllowed(true);
		tableModules.setCellSelectionEnabled(true);
		tableModules.setFillsViewportHeight(true);
		tableModules.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		tableModules.setModel(new DefaultTableModel( rowData, columnNames ){
				@SuppressWarnings("rawtypes")
				Class[] columnTypes = new Class[] {
					Integer.class, String.class, String.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class
				};
				@SuppressWarnings({ "unchecked", "rawtypes" })
				public Class getColumnClass(int columnIndex) {
					return columnTypes[columnIndex];
			}
		});  
	
		tabbedPaneContent.addTab("Notentabelle", null, new JScrollPane(tableModules), "Noten als Tabelle");
		tabbedPaneContent.setEnabledAt(0, true);
		
		panelDiagram = new Diagram();
		tabbedPaneContent.addTab("Semestergrafik", null, panelDiagram, "Kleine Visuelle Darstellung der Semsterdurchschnitte");
		tabbedPaneContent.setEnabledAt(1, true);
		panelDiagram.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		
			
		textPanelStatistics = new JTextPane();
		JScrollPane spStatistics = new JScrollPane(textPanelStatistics); 
		textPanelStatistics.setText("Noch keine Daten für die Statistik vorhanden.\n");
		tabbedPaneContent.addTab("Statistiken", null, spStatistics, "Durchschnitt etc.");
		
		JTextArea txtrInfo = new JTextArea();
		txtrInfo.setText("Die Oberfläche befindet sich noch im Aufbau.\n\nBisher sind nur die Buttons Login setzen und \nNoten laden (QIS) Implementiert.\nDie Menue und Parametersteuerung funktioniert jedoch vollstaendig.\n\nBugs an tim.malich@gmail.com senden.");
		tabbedPaneContent.addTab("Info", null, txtrInfo, null);
		tabbedPaneContent.setEnabledAt(3, true);
		setVisible(true);
		
		
		/* creates the checkbox for the popup */
		chckbxSaveNoLogin = new JCheckBox("Logindaten beim Speichern auslassen");
		chckbxSaveNoLogin.setToolTipText("Passwort und Matrikelnummer werden beim Speichern nicht mit in deiner Noten.xml Datei gespeichert.");
		chckbxSaveNoLogin.setHorizontalAlignment(SwingConstants.CENTER);
		
		/* Add Listeners ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
		 /* synchronizes the checkboxes of the popups */
		chckbxSaveNoLogin.addItemListener( new ItemListener() {
			public void itemStateChanged(ItemEvent ie) {
				// ask for chckbxSaveNoLogin doesn't work. i don't no why.*/
				if( null != popLogin && null != popLogin.chckbxSaveNoLogin )
					popLogin.chckbxSaveNoLogin.setSelected(chckbxSaveNoLogin.isSelected());
				if( null != popSave && null != popSave.chckbxSaveNoLogin )
					popSave.chckbxSaveNoLogin.setSelected(chckbxSaveNoLogin.isSelected());
			}
		});	
		
		btnBeenden.addActionListener(new HandlebtnBeenden());
		/* End add Listeners ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	}
	
	public void setSemNoten(ArrayList<SemNote> semNoten){
		this.panelDiagram.semNoten=semNoten;
	}
	/* opens the login popup and creates it if it isn't existing */
	public void openPopLogin(){
		if( null == popLogin )
			popLogin = new PopupLogin("Logindaten", chckbxSaveNoLogin);
		this.placeScreenMid(popLogin);
		this.popLogin.setVisible(true);
		this.popLogin.resetFailureMsg();
	}
	
	public void openPopLogin(String matrikel, String pw){
		openPopLogin();
		popLogin.setMatrikel(matrikel);
		popLogin.setPassword(pw);
	}
		
	public void openPopSave(){
		if( null == popSave )
			popSave = new PopupSaveFile("Datenstruktur speichern", chckbxSaveNoLogin);
		
		
		this.placeScreenMid(popSave);
		this.popSave.setVisible(true);
		
	}

	// place the popup in the screen mid
	void placeScreenMid( JFrame Frame){
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension windowSize = this.getSize();
                        
        Frame.setLocation(( (screenSize.width  - windowSize.width ) / 2), ((screenSize.height - windowSize.height) / 2) );      
	}
	
	
	/* simple code to implement a diagram, not so pretty, just writing for experimenting a little bit with paint */
	/*void addNote(double note, String semester){
		this.noten.add(new Note(note,semester));
	}
	// helper class for Diagram values
	class Note{
		public double note;
		public String semester;
		Note(double note, String semester){
			this.note=note;
			this.semester=semester;
		}
	}*/
	// simple class for drawing a diagram
	class Diagram extends JPanel{
		public ArrayList<SemNote> semNoten;
		public Diagram(ArrayList <SemNote> semNoten){
			this.semNoten = semNoten;
		}
		public Diagram(){semNoten = null;}
		@Override public void paintComponent(Graphics g) {
			super.paintComponent(g);
			//the origin
			double edgeDist=0.1; // distance to the border f.e. 0.1 for 10%
			Point origin = new Point((int)(edgeDist*getWidth()), (int)((1-edgeDist)*getHeight()));
			int maxAbscissa = (int)((1-edgeDist)*getWidth()); // right value on x axis
			int minAbscissa = (int)(edgeDist*getWidth());     // left value on  x axis
			int maxOrdinate = (int)((edgeDist)*getHeight());  // highest value on y axis
			int minOrdinate = (int)((1-edgeDist)*getHeight());
			int width = maxAbscissa - minAbscissa;            // length x axis
			int height = minOrdinate - maxOrdinate;           // length y axis
			
			// draw y axis (the ordinate)
			g.drawLine(origin.x, origin.y, maxAbscissa, minOrdinate);
			double maxNote = 5.0;
			for(double i=1.0; i<=maxNote; i++){
				g.drawLine(origin.x, (int)(origin.y-i/maxNote*height), (origin.x-7), (int)(origin.y-i/maxNote*height));
				g.drawString(Double.toString(i),origin.x-25, (int)(origin.y-i/5*height));
			}
			// draw x-axis
				g.drawLine(origin.x, origin.y, (int)minAbscissa, (int)maxOrdinate);
			
			
			if(null == semNoten || semNoten.size() < 1 )
				return; // no marks giver :(
			
			// first point
			Point lastPoint = null;
			//lastPoint = new Point((int)(origin.x+(double)1/semNoten.size()*width), (int)(origin.y-(height/maxNote*semNoten.get(0).getAvg())));
			lastPoint = new Point(origin.x, (int)(origin.y-(height/maxNote*semNoten.get(0).getAvg())));
			
			// x axis labeling + draw line
			for(int i=0; i<semNoten.size(); i++){
				int x = (int)(origin.x+(double)i/semNoten.size()*width); // x distance
				// label X-axis
				g.drawLine(x, origin.y, x, origin.y+7);
				// quick'n dirty string cut; usually it's a very bad idea to do this here. But: #YOLO ;)
				String tmp = semNoten.get(i).getSemester().replaceAll("Wintersemester", "WS").replaceAll("Sommersemester", "SS");
				g.drawString(tmp,x, origin.y+20);
				
				// draw the line
				int newY =(int)(origin.y-(height/maxNote*semNoten.get(i).getAvg()));
				tmp=Float.toString((float)(((int)(semNoten.get(i).getAvg()*100))/100.0));
				g.drawString(tmp, x, newY+15);
				if( newY < lastPoint.y ){
					g.setColor(Color.RED);
				}else if( newY > lastPoint.y){
					g.setColor(Color.GREEN);
				}
				g.drawLine(lastPoint.x, lastPoint.y, x, newY);
				g.setColor(Color.BLACK);
				lastPoint.x=x;
				lastPoint.y=newY;
			}	        
	    }
	}
	
	/* Handlers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	class HandlebtnBeenden implements ActionListener{
		public void actionPerformed(ActionEvent evt){
			System.exit(0);
		}
	}
}
